using System;
using UnityEngine;

/****************************************************
// 功能：计时器
// | Talk To [ 聊来改善地区金融服务环境，助力企业发展 ]
// | Copyright (c) 2021-2025 聊来 All rights reserved.
// | Licensed ( <a href="http://www.apache.org/licenses/LICENSE-2.0">聊来</a> )
// | @Author: 贯彻己道的云 <18970881148@qq.com>
// | DateTime: 2025/4/8 11:29:25
*****************************************************/

public class MonoTimer
{
    public Action<float> OnTimeUpdated;
    public Action OnTimeCompleted;

    // 总时间 单位：s
    private readonly float duration;
    // 剩余时间
    private float remainingTime;
    private bool isRunning;
    // 上一秒记录
    private float lastSeconds;

    public MonoTimer(float duration)
    {
        this.duration = duration;
        Reset();
    }


    /// <summary>
    /// 开始计时
    /// </summary>
    public void Start()
    {
        remainingTime = duration;
        isRunning = true;
        lastSeconds = Mathf.CeilToInt(duration);
    }

    /// <summary>
    /// 暂停计时
    /// </summary>
    public void Pause()
    {
        isRunning = false;
    }

    /// <summary>
    /// 继续计时
    /// </summary>
    public void Resume()
    {
        isRunning = true;
    }

    /// <summary>
    /// 重置计时器
    /// </summary>
    public void Reset()
    {
        remainingTime = duration;
        isRunning = false;
        lastSeconds = duration;
    }

    /// <summary>
    /// TODO 更新计时，给外部Update Time.DeltaTime驱动，后续还可以扩展
    /// </summary>
    /// <param name="deltaTime"></param>
    public void Tick(float deltaTime)
    {
        if (!isRunning) return;

        remainingTime -= deltaTime;
        var currentSeconds = remainingTime;
        
        // 每秒触发更新
        if (Math.Abs(currentSeconds - lastSeconds) > 0)
        {
            lastSeconds = currentSeconds;
            OnTimeUpdated?.Invoke(currentSeconds);
        }

        // 计时器结束
        if (remainingTime > 0) return;
        remainingTime = 0;
        isRunning = false;
        OnTimeUpdated?.Invoke(0);
        OnTimeCompleted?.Invoke();

        OnTimeUpdated = null;
        OnTimeCompleted = null;
    }
}
